import re
import csv
import json
import logging
from pymediainfo import MediaInfo
from ffmpy import FFmpeg
from pathlib import Path

def new_folder(target_folder, vp):
    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
    try:
        if not target_folder:  # 如果target_folder为空
            path = Path(vp)
            if not path.exists():   # 验证路径是否存在
                raise ValueError(f"The path {vp} does not exist.")               
            file_name = path.stem   # 提取无后缀(suffix)的文件名
            target_folder = path.parent / file_name  # 使用文件名创建新的目标文件夹
        if not target_folder.exists():
            target_folder.mkdir(parents=True)
            logging.info(f"--- 创建了新的文件夹在{target_folder} ---")
        else:
            logging.info("---  已经有这个文件夹!  ---")
    except ValueError as e:
        logging.error(f"路径验证错误: {e}")
    except PermissionError as pe:
        logging.error(f"权限错误: {pe}")
    except Exception as e:
        logging.error(f"未知错误: {e}")
    return target_folder

def format_duration(duration_str):
    # 使用正则表达式匹配时间信息
    hours = 0
    minutes = 0
    seconds = 0
    # 匹配小时、分钟和秒
    hours_match = re.search(r'(\d+)\s*h', duration_str)
    if hours_match:
        hours = int(hours_match.group(1))

    minutes_match = re.search(r'(\d+)\s*min', duration_str)
    if minutes_match:
        minutes = int(minutes_match.group(1))
    
    seconds_match = re.search(r'(\d+)\s*s', duration_str)
    if seconds_match:
        seconds = int(seconds_match.group(1))

    formatted_duration = '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
    return formatted_duration

# 测试不同格式的时间信息
print(format_duration("2 min 27 s"))  # 输出: 00:02:27
print(format_duration("1 h 6 min"))   # 输出: 01:06:00
print(format_duration("1 h 3 min 09 s"))  # 输出: 01:03:09

def apend_endtime(csv_input_path):
    duration = '40:09'
    # 读取CSV文件
    with open(csv_input_path, 'r', encoding='utf-8') as file:
        reader = csv.reader(file, delimiter=' ')  # 假设你的CSV文件使用制表符作为分隔符
        rows = [row for row in reader]
    # 生成第三列endtime
    for i in range(len(rows) - 1):
        if len(rows[i+1]) > 1:  # 检查行数是否足够来避免IndexError
            rows[i].append(rows[i+1][1])  # 复制下一行的starttime作为endtime
        else:
            rows[i].append('')  # 如果行数不足，以空字符串填充endtime
    # 处理最末行的endtime
    if len(rows) > 0:
        if len(rows[-1]) < 2:
            rows[-1].append('')  # 如果行数不足，以空字符串填充endtime
        rows[-1].append(duration)  # 最末行的endtime设置为'duration'

    print(rows)
    return rows

def m_info(vp):
    media_info = json.loads(MediaInfo.parse(vp).to_json())
    # print(media_info)
    film_info = []
    for track in media_info['tracks']:
        track_type = track.get('track_type', '')
        if track_type in ['Video', 'Audio']:
            try:
                bit_rate = int(track['bit_rate'])
            except (KeyError, ValueError):
                bit_rate = None  
            if track_type == 'Video':
                try:
                    sampled_width = int(track['sampled_width'])
                    sampled_height = int(track['sampled_height'])
                except (KeyError, ValueError):
                    sampled_width = sampled_height = None                 
                info = {
                    '视频码率': '%dkb' % (bit_rate / 1000) if bit_rate is not None else '',
                    '宽高比': '%dX%d' % (sampled_width, sampled_height) if sampled_width and sampled_height else '',
                    '视频格式': track.get('format', ''),
                    '帧率': int(float(track['frame_rate'])) if 'frame_rate' in track else '',
                    '视频流大小': '%.2f MB' % (track['stream_size'] / 1024**2) if 'stream_size' in track else '',
                    '时长': track['other_duration'][0] if 'other_duration' in track and track['other_duration'] else ''
                }
                
            elif track_type == 'Audio':
                info = {
                    '音频格式': track.get('format', ''),
                    '音频码率': '%dkb' % (bit_rate / 1000) if bit_rate is not None else '',
                    '时长': track['other_duration'][0] if 'other_duration' in track and track['other_duration'] else '',
                    '音频流大小': '%.2f MB' % (track['stream_size'] / 1024**2) if 'stream_size' in track else ''
                }
            try:
                film_info.append(info)
            except Exception as e:
                # 更细致的异常处理可以在这里增加
                print(f"Error processing track info: {e}")
    return film_info

if __name__ == "__main__":
    """
    处理音频文件的函数。
    - video_path: 原始视频文件的路径。
    - csv_file_path: 包含音频分割信息的CSV文件路径。
    - output_folder: 输出音频片段的存储文件夹。

    """
    csv_input_path = r"/Volumes/ST/Documents/Downloads/关淑怡《难得有情人》.txt"
    apend_endtime(csv_input_path)